/**
 * Copyright (C) 2008 GeoScheduler Team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */

package org.geoscheduler.rest;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import org.geoscheduler.Context;
import org.geoscheduler.commons.marshaller.JSONMarshaller;
import org.geoscheduler.commons.msgs.BasicMessageSeverities;
import org.geoscheduler.commons.msgs.Message;
import org.geoscheduler.commons.msgs.ParametrizedMessage;
import org.geoscheduler.commons.msgs.types.GeneralMsgs;
import org.geoscheduler.commons.tools.AssertTools;
import org.geoscheduler.dao.AccountDAO;
import org.geoscheduler.dao.AccountLocationDAO;
import org.geoscheduler.dao.EventDAO;
import org.geoscheduler.dao.LocationDAO;
import org.geoscheduler.dao.TagDAO;
import org.geoscheduler.dao.TokenDAO;
import org.geoscheduler.exceptions.JSONWrappedException;
import org.geoscheduler.rest.utils.JSONResult;
import org.geoscheduler.rest.utils.OperationState;
import org.geoscheduler.security.authenticate.AuthenticatorProvider;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 
 * <h2>AbstractResource</h2>
 * <p>
 * Supertype for application resources
 * </p>
 * 
 * @author lko
 */
public abstract class AbstractResource {

	private Context ctx;

	protected AbstractResource() {
		// empty
	}

	/**
	 * @param message
	 * @return {@link Message} object transformed to valid json application
	 *         result.
	 */
	protected JSONObject response(Message message) {
		try {
			return response((message.getSeverity().compareTo(BasicMessageSeverities.INFO) > 0 ? OperationState.ERROR
					: OperationState.OK), getContext().getMsgMarshaller().marshall(message, ctx.getLocale()));
		} catch (JSONException ex) {
			throw new IllegalStateException("failed to create JSON representation of message " + message, ex);
		}
	}

	/**
	 * 
	 * @param state
	 * @param value
	 * @return json encoded result of operation
	 */
	public JSONObject response(OperationState state, Object value) {
		try {
			if (value instanceof JSONWrappedException) {
				state = OperationState.ERROR;
				value = ((JSONWrappedException) value).getMessage(getContext());
			} else if (value instanceof Throwable) {
				value = new ParametrizedMessage(GeneralMsgs.UNKNOWN_ERROR, ((Throwable) value).getMessage());
			} else if (value instanceof Map) {
				value = new JSONObject((Map<String, Object>) value);
			} else if (value instanceof Iterator) {
				Collection<Object> values = new ArrayList<Object>();
				Iterator<?> it = (Iterator<?>) value;
				while (it.hasNext()) {
					values.add(it.next());
				}
				value = new JSONArray(values);
			}
			// Check if already wrapped in JSON object
			if (!((value instanceof JSONObject) || (value instanceof JSONArray))) {
				value = getContext().getMarshaller().marshall(value, new JSONObject());
			}
			return JSONResult.valueOf(state, value);
		} catch (JSONException e) {
			throw new IllegalStateException("failed to create response JSON object");
		}
	}

	protected JSONObject response(Exception value) {
		return response(OperationState.ERROR, value);
	}

	protected JSONObject response(Object value) {
		return response(OperationState.OK, value);
	}

	// Getters & Setters

	public Context getContext() {
		return AssertTools.assertNotNull(this.ctx, "context for {0} not initialized", this.toString());
	}

	public void setContext(Context ctx) {
		this.ctx = ctx;
	}

	// Facade methods

	protected AuthenticatorProvider getAuthProvider() {
		return getContext().getAuthenticatorProvider();
	}

	protected AccountDAO getAccountDAO() {
		return getContext().getAccountDAO();
	}

	protected EventDAO getEventDAO() {
		return getContext().getEventDAO();
	}

	protected LocationDAO getLocationDAO() {
		return getContext().getLocationDAO();
	}

	protected AccountLocationDAO getAccountLocationDAO() {
		return getContext().getAccountLocationDAO();
	}

	protected TokenDAO getTokenDAO() {
		return getContext().getTokenDAO();
	}

	protected TagDAO getTagDAO() {
		return getContext().getTagDAO();
	}

	protected JSONMarshaller getMarshaller() {
		return getContext().getMarshaller();
	}

}
